import type { FormInstance, FormItemProp } from "element-plus";
import type { Ref } from "vue";
import { cloneDeep } from "es-toolkit";
import { ref } from "vue";

// 全局状态, 保持统一
const isDisabled = ref(false);
const timer = ref<NodeJS.Timeout | undefined>(undefined);
const text = ref("");

export const useVerifyCode = (): {
    isDisabled: Ref<boolean>;
    timer: Ref<NodeJS.Timeout | undefined>;
    text: Ref<string>;
    start: (formEl: FormInstance | undefined, props: FormItemProp, time?: number) => Promise<void>;
    end: () => void;
} => {
    const start = async (formEl: FormInstance | undefined, props: FormItemProp, time = 60): Promise<void> => {
        if (!formEl) return;
        const initTime = cloneDeep(time);
        await formEl.validateField(props, (isValid) => {
            if (isValid) {
                clearInterval(timer.value);
                isDisabled.value = true;
                text.value = `${time}`;
                timer.value = setInterval(() => {
                    if (time > 0) {
                        time -= 1;
                        text.value = `${time}`;
                    } else {
                        text.value = "";
                        isDisabled.value = false;
                        clearInterval(timer.value);
                        time = initTime;
                    }
                }, 1000);
            }
        });
    };

    const end = (): void => {
        text.value = "";
        isDisabled.value = false;
        clearInterval(timer.value);
    };

    return {
        isDisabled,
        timer,
        text,
        start,
        end,
    };
};
